﻿#include "dtuwindow.h"
#include "dtuadddialog.h"
#include "dtusearchdialog.h"
#include "dtuexportdialog.h"
#include "../../include/macro.h"

DTUWindow::DTUWindow()
{
    setup_ui();
    setup_model();
    setup_ui_slots();
    /**/

    //sql
    sqlThread = new SqlThread("dtu","dtuManage");
    //add
    connect(this, &DTUWindow::sig_addDTU, sqlThread, &SqlThread::slt_addDTU);
    connect(sqlThread, &SqlThread::sig_lastId, this, &DTUWindow::slt_addgetId);
    //delete
    connect(this, &DTUWindow::sig_deleteDTU, sqlThread, &SqlThread::slt_deleteDTU);
    //update
    connect(dtuSettingWidget->okButton,&QPushButton::clicked, this, &DTUWindow::confirmSetting);
    connect(this, &DTUWindow::sig_updateDTU, sqlThread, &SqlThread::slt_updateDTU);
    sqlThread->start();



    tcpThread = new TCPThread(31, 15383);
    //connect(tcpThread, &TCPThread::sig_dtuUpdate, chartManager, &ChartManager::slt_updateChart);
    connect(tcpThread, &TCPThread::sig_dtuUpdate, this, &DTUWindow::slt_updateCurrent);


    tcpThread2 = new TCPThread(40, 55016);
    //connect(tcpThread2, &TCPThread::sig_dtuUpdate, chartManager, &ChartManager::slt_updateChart);
    connect(tcpThread2, &TCPThread::sig_dtuUpdate, this, &DTUWindow::slt_updateCurrent);


    //tcp sql upload
    uploadThread = new SqlThread("dtu","dtuUpload");
    connect(tcpThread, &TCPThread::sig_dtuUpload, uploadThread, &SqlThread::slt_uploadCurrent);
    uploadThread->start();

    uploadThread2 = new SqlThread("dtu","dtuUpload2");
    connect(tcpThread2, &TCPThread::sig_dtuUpload, uploadThread2, &SqlThread::slt_uploadCurrent);
    uploadThread2->start();
/**/
    //sql search
    searchThread = new SqlThread("dtu","dtuSearch");
    connect(this, &DTUWindow::sig_searchCurrent, searchThread, &SqlThread::slt_searchCurrent);
    connect(searchThread, &SqlThread::sig_searchCurrent, hisChart, &HisChart::slt_updateSeries);
    searchThread->start();

    tcpThread->start();
    tcpThread2->start();//

}

DTUWindow::~DTUWindow()
{

    tcpThread->quit();
    tcpThread->wait();
    tcpThread2->quit();
    tcpThread2->wait();
    uploadThread->quit();
    uploadThread->wait();
    uploadThread2->quit();
    uploadThread2->wait();
    sqlThread->quit();
    sqlThread->wait();
}


void DTUWindow::confirmSetting()
{
    QModelIndex index = dtuTableView->currentIndex();
    if(index.isValid() && dtuSettingWidget->checkSetting())
    {
        DTUData data = m_modelDTUTable->getDeviceData(index);
        QString name = dtuSettingWidget->name_ed->text();
        QString pos = dtuSettingWidget->pos_ed->text();
        if(name != data.name || pos != data.position)
        {
            data.name = name;
            data.position = pos;
            emit sig_updateDTU(data);
            m_modelDTUTable->setDeviceData(index, data);
            dtuSettingWidget->setInfo(data);
        }
    }
    else
    {
        QMessageBox::warning(NULL, QStringLiteral("设置失败"), QStringLiteral("未选择设备"));
    }
}

void DTUWindow::setup_ui_slots()
{
    //lines
    connect(rtButtonGroup,QOverload<int, bool>::of(&QButtonGroup::buttonToggled),
            chartManager, &ChartManager::slt_dtuRouteSwtich);
    connect(hisButtonGroup,QOverload<int, bool>::of(&QButtonGroup::buttonToggled),
            hisChart, &HisChart::slt_dtuRouteSwtich);
    //table
    connect(dtuTableView, &QTableView::clicked, this, &DTUWindow::slt_dtuSelected);
    connect(dtuTableView, &QTableView::customContextMenuRequested, this, &DTUWindow::slt_showMenu);
    connect(deleteAction, &QAction::triggered, this, &DTUWindow::slt_delete);
    //history
    connect(addButton, &QAbstractButton::clicked, this, &DTUWindow::slt_addDialog);
    connect(searchButton,  &QAbstractButton::clicked, this, &DTUWindow::slt_searchDialog);
    connect(exportButton,  &QAbstractButton::clicked, this, &DTUWindow::slt_exportDialog);
}

void DTUWindow::slt_delete()
{
    auto index = dtuTableView->currentIndex();
    emit sig_deleteDTU(m_modelDTUTable->getDeviceId(index));
    m_modelDTUTable->deleteDevice(index);
}

void DTUWindow::slt_showMenu(const QPoint& point)
{
    auto index = dtuTableView->indexAt(point);
    if (index.isValid())
    {
        menu->exec(QCursor::pos());
    }
}

void DTUWindow::slt_addgetId(uint id)
{
    m_modelDTUTable->lastDevice().id = id;
    chartManager->addDTU(id);
}

void DTUWindow::slt_addDialog()
{
    // add dialog
    DTUAddDialog dialog;
    if(dialog.exec())
    {
        qDebug()<< "dtu add dialog"<<endl;
        DTUData data;
        data.name = dialog.name_ed->text();
        data.position = dialog.pos_ed->text();
        memset(data.current, 0 ,sizeof(int)*4);
        m_modelDTUTable->addDevice(data);
        emit sig_addDTU(data);
    }
}

void DTUWindow::slt_searchDialog()
{
    DTUSearchDialog dialog;
    if(dialog.exec())
    {
        QDateTime start = dialog.time_start_ed->dateTime();
        QDateTime end = dialog.time_end_ed->dateTime();
        int row = dialog.id_box->value();
        if(row >= m_modelDTUTable->size() || start >= end || start > QDateTime::currentDateTime())
            QMessageBox::warning(NULL,  QStringLiteral("搜索条件不合法"),
                                  QStringLiteral("确保序号正确，终止时间晚于起始时间晚于目前时间"));
        else
        {
            const DTUData& data = m_modelDTUTable->getDeviceData(row);
            emit sig_searchCurrent(start, end, data.id);
            timelabel->setText(QString("DTU %1 : ").arg(data.name)
                               + start.toString("ddd yyyy-MM-dd hh:mm:ss")
                               + "~" + end.toString("ddd yyyy-MM-dd hh:mm:ss"));
        }
    }
}

void DTUWindow::slt_exportDialog()
{
    DTUExportDialog dialog;
    if(dialog.exec())
    {
        QDateTime start = dialog.time_start_ed->dateTime();
        QDateTime end = dialog.time_end_ed->dateTime();
        //int id = dialog.id_box->value();
        //export signal
    }
}

void DTUWindow::slt_dtuSelected(const QModelIndex &index)
{
    const DTUData& dtu = m_modelDTUTable->getDeviceData(index);
    dtuSettingWidget->setInfo(dtu);
    chartManager->slt_dtuSwitch(dtu.id);
}

void DTUWindow::slt_updateCurrent(uint id, const QList<int>& data)
{
    chartManager->updateChart(id, data);
    m_modelDTUTable->updateCurrent(id, data);
}

void DTUWindow::setup_model()
{
    m_modelDTUTable = new DTUTableModel();

    chartManager = new ChartManager(dtuRTLine);

    hisChart = new HisChart();
    dtuHisLine->setChart(hisChart);

    QList<DTUData> dtulist;
    {
        QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL", "dtu temp");
        db.setHostName("localhost");
        db.setPort(3306);
        db.setDatabaseName("dtu");
        db.setUserName(TO_STR(DB_USERNAME));
        db.setPassword("");
        db.open();
        if(!db.open())
        {
            qDebug()<<"mysql: initial connect dtu error"<<db.lastError().text();
            return;
        }
        else
             qDebug()<<"mysql: initial connect dtu  OK";

        QString str("SELECT * FROM dtu.info");
        QSqlQuery query(str,db);
        query.exec();
        while(query.next())
        {
            DTUData data;
            data.id = query.value(0).toInt();
            data.ip = query.value(1).toInt();
            data.name = query.value(2).toString();
            data.position = query.value(3).toString();
            memset(data.current, 0, 4*sizeof(int));
            dtulist.append(data);

            chartManager->addDTU(data.id);
        }
        db.close();
    }
    QSqlDatabase::removeDatabase("dtu temp");

    dtuRTLine->setChart(chartManager->currentChart());

    m_modelDTUTable->setList(dtulist);
    QStringList header2;
    header2<<"DTU"<<"ROUTE 1"<<"ROUTE 2"<<"ROUTE 3"<<"ROUTE 4";
    m_modelDTUTable->setHorizontalHeader(header2);

    dtuTableView->setModel(m_modelDTUTable);
    setup_tableview();

}
//uis
void DTUWindow::setup_ui()
{
    QGridLayout* layout = new QGridLayout();
    int w = 3, h = 8;
    int dtuview_w = 1;
    int dtuview_h = 7;
    dtuSettingWidget = new DTUSettingWidget();
    layout->addLayout(setup_dtutable(), 0, 0, dtuview_h, dtuview_w);
    layout->addLayout(setup_dtulines(),  0, dtuview_w, h, w - dtuview_w);
    layout->addWidget(dtuSettingWidget, dtuview_h, 0, h - dtuview_h+1, dtuview_w);
    layout->setMargin(0);
    layout->setSpacing(1);
    setLayout(layout);
}

QLayout* DTUWindow::setup_dtutable()
{
    QGridLayout* layout = new QGridLayout();

    QLabel* dtuTitle = new QLabel(QStringLiteral("DTU实时数据"));
    dtuTitle->setAlignment(Qt::AlignCenter);
    dtuTitle->setStyleSheet("background-color:#d4d0c8;");

    addButton = new QToolButton();
    addButton->setIcon(QIcon(":/pics/rc/add.jpg"));

    dtuTableView = new QTableView;
    dtuTableView->setContextMenuPolicy(Qt::CustomContextMenu);
    menu = new QMenu(dtuTableView);
    deleteAction = new QAction(QStringLiteral("删除设备"));
    menu->addAction(deleteAction);

    layout->addWidget(dtuTitle,0,0,1,3);
    layout->addWidget(addButton,0,3,1,1);
    layout->addWidget(dtuTableView,1,0,5,4);

    return layout;
}

void DTUWindow::setup_tableview()
{
    dtuTableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    dtuTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    dtuTableView->setSelectionMode(QAbstractItemView::SingleSelection);
}

QLayout* DTUWindow::setup_dtulines()
{
    QVBoxLayout* layout = new QVBoxLayout();

    //rtline container
    QLayout* rtlineContainer = setup_rtline();
    //hisline container
    QLayout* hislineContainer = setup_hisline();

    layout->setSizeConstraint(QLayout::SetMinimumSize);
    layout->addLayout(rtlineContainer);
    layout->addLayout(hislineContainer);

    return layout;
}

QLayout* DTUWindow::setup_rtline()
{
    QGridLayout* layout = new QGridLayout();
    QLabel* rtlabel = new QLabel(QStringLiteral("DTU实时曲线"));
    rtlabel->setAlignment(Qt::AlignCenter);
    rtlabel->setStyleSheet("background-color:#d4d0c8;");
    rtButtonGroup = new QButtonGroup();
    rtButtonGroup->setExclusive(false);
    QRadioButton* radiobutton[4];
    const QString color[4] = {"(255,100,100);","(100,255,100);",
                              "(120,120,255);","(240,240,0);"};
    for(int i=0;i<4;i++)
    {
        radiobutton[i] = new QRadioButton("ROUTE "+QString::number(i+1));
        radiobutton[i]->setChecked(true);
        radiobutton[i]->setStyleSheet("font: 12px \"Microsoft YaHei\";height: 10px;"
                                      "border-color:rgb(200,200,200);"
                                      "border-style:solid;"
                                      "border-radius:5px;border-width: 1px;"
                                      "background-color:rgb" + color[i]);
        rtButtonGroup->addButton(radiobutton[i], i);

    }
    dtuRTLine = new QChartView();
    layout->addWidget(rtlabel,0,0,1,4);
    for(int i=0;i<4;i++)
        layout->addWidget(radiobutton[i], 1, i);
    layout->addWidget(dtuRTLine,2,0,19,4);
    return layout;
}

QLayout* DTUWindow::setup_hisline()
{
    QGridLayout* layout = new QGridLayout();
    QLabel* hislabel = new QLabel(QStringLiteral("DTU历史曲线"));
    hislabel->setStyleSheet("background-color:#d4d0c8;");
    hislabel->setAlignment(Qt::AlignCenter);
    dtuHisLine = new QChartView();
    searchButton = new QToolButton();
    exportButton = new QToolButton();
    searchButton->setIcon(QIcon(":/pics/rc/search.jpg"));
    exportButton->setIcon(QIcon(":/pics/rc/export.jpg"));
    timelabel = new QLabel("start time ~ end time");
    timelabel->setStyleSheet("font: 12px;");


    hisButtonGroup = new QButtonGroup();
    hisButtonGroup->setExclusive(false);
    QRadioButton* radiobutton[4];
    const QString color[4] = {"(255,100,100);","(100,255,100);",
                              "(120,120,255);","(240,240,0);"};
    for(int i=0;i<4;i++)
    {
        radiobutton[i] = new QRadioButton("ROUTE "+QString::number(i+1));
        radiobutton[i]->setChecked(true);
        radiobutton[i]->setStyleSheet("font: 12px \"Microsoft YaHei\";height: 10px;"
                                      "border-color:rgb(200,200,200);"
                                      "border-style:solid;"
                                      "border-radius:5px;border-width: 1px;"
                                      "background-color:rgb" + color[i]);
        hisButtonGroup->addButton(radiobutton[i], i);
        radiobutton[i]->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    }

    layout->addWidget(hislabel,0,0,1,20);
    layout->addWidget(timelabel,1,0,1,18);
    layout->addWidget(searchButton,1,18,1,1);
    layout->addWidget(exportButton,1,19,1,1);
    for(int i=0;i<4;i++)
    {
        layout->addWidget(radiobutton[i], 2, 5 * i, 1, 5);
    }
    layout->addWidget(dtuHisLine,3,0,19,20);
    return layout;
}



